"""
@文件: access.py
@Author: ZJJ
@Email: 1065377805@qq.com
@Time: 2025/3/31
@Des:权限管理
"""
from fastapi import APIRouter, Security
from tortoise.expressions import F

from core.Auth import check_permission
from core.Response import fail, success
from model.base import Access, Role
from schemas import base, role

router = APIRouter(prefix="/access")


@router.post("/add_access", summary="添加权限")
async def add_access(post: role.CreateAccess):
    #超级管理员可以创建权限
    check = await Access.get_or_none(scopes=post.scopes)
    if check:
        return fail(msg=f"scope {post.scopes} 已经存在")
    result = await Access.create(**post.model_dump())
    if not result:
        return fail(msg="创建失败")
    return success(msg="创建成功")


@router.get('/all_access',
            summary="权限查询",
            # dependencies=[Security(check_permission, scopes=["role_access"])]
            )
async def get_all_access(role_id: int):
    """
    获取全部权限
    :return:
    """
    result = await Access.annotate(key=F('id'), title=F('access_name')).all().values("key", "title", "parent_id")
    # 当前角色权限
    role_access = await Access.filter(role__id=role_id).values_list('id')

    # 系统权限
    tree_data = access_tree(result, 0)
    # 角色权限
    role_access = [i[0] for i in role_access]
    data = {
        "all_access": tree_data,
        "role_access": role_access
    }
    return success(msg="当前用户可以下发的权限", data=data)


@router.put("/set_role", summary="权限设置",
             # dependencies=[Security(check_permission, scopes=["role_access"])],
             # response_model=base.BaseResp
             )
async def set_role_access(post: role.SetAccess):
    """
    设置角色权限
    :param post:
    :return:
    """
    print("12")
    # 获取当前角色
    role_data = await Role.get_or_none(id=post.role_id)
    if not role_data:  # 检查角色是否存在
        return fail(msg=f"角色ID {post.role_id} 不存在")
    # 清空权限
    await role_data.access.clear()
    # 无设置权限
    if not post.access:
        return success(msg="已清空当前角色所有权限!")
    # 获取分配的权限集合
    access = await Access.filter(id__in=post.access, is_check=True).all()
    # 添加权限
    await role_data.access.add(*access)
    return success(msg="保存成功!")


def access_tree(data, pid):
    """
    遍历权限树
    :param data: rule[]
    :param pid: 父ID
    :return: list
    """
    result = []
    for item in data:
        if pid == item["parent_id"]:
            temp = access_tree(data, item["key"])
            if len(temp) > 0:
                # item["key"] = str(item["key"])
                item["children"] = temp
            result.append(item)
    return result
